package cn.interestinghop.dao;

import cn.interestinghop.model.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl extends BaseDao<C> implements UserDao{
    @Override
    public User GetAll(String account, String password) {
        Connection conn = getConnection();
        PreparedStatement pstm = null;
        ResultSet rs = null;
        String sql = "SELECT id,account,nick_name,password,gender,id_card_no,email,phone,type,open_id FROM t_user WHERE account=? and password=?";
        User user = null;
        try {
            pstm = conn.prepareStatement(sql);
            pstm.setString(1,account);
            pstm.setString(2,password);
            rs = pstm.executeQuery();
            if (rs.next()){
                user = new User(rs.getInt("id"),
                        rs.getString("account"),
                        rs.getString("nick_name"),
                        rs.getString("password"),
                        rs.getInt("gender"),
                        rs.getString("id_card_no"),
                        rs.getString("email"),
                        rs.getString("phone"),
                        rs.getInt("type"),
                        rs.getString("open_id"));
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            closeAll(conn,pstm,rs);
        }
        return user;
    }

    @Override
    public int add(User user) {
        int add = 0;
        Connection conn = getConnection();
        String sql = "INSERT INTO t_user (account,nick_name,password,gender,email,phone) VALUES (?,?,?,?,?,?)";
        PreparedStatement pstm = null;
        try {
            pstm = conn.prepareStatement(sql);
            pstm.setString(1,user.getAccount());
            pstm.setString(2,user.getNick_name());
            pstm.setString(3,user.getPassword());
            pstm.setInt(4,user.getGender());
            pstm.setString(5,user.getEmail());
            pstm.setString(6,user.getPhone());
            add = pstm.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            closeAll(conn,pstm,null);
        }
        return add;
    }
}
